
import { Application } from 'egg';
import { INTEGER, MEDIUMINT, Instance } from 'sequelize';

export interface IArticleLikeAttr {
  id?: number;
  status?: number;
  articleId: number;
  userId: number;
}

interface IArticleLikeInst extends Instance<IArticleLikeAttr>, IArticleLikeAttr { }

export default (app: Application) => {
  const model = app.model.define<IArticleLikeInst, IArticleLikeAttr>('article_like', {
    id: {
      type: MEDIUMINT(8).UNSIGNED,
      allowNull: false,
      autoIncrement: true,
      primaryKey: true,
    },
    status: {
      type: INTEGER,
      allowNull: false,
      defaultValue: 1,    // 0删除
    },
    articleId: {
      type: MEDIUMINT(8).UNSIGNED,
      allowNull: false,
    },
    userId: {
      type: MEDIUMINT(8).UNSIGNED,
      allowNull: false,
    },
  }, {
    timestamps: true,
    paranoid: false,
    charset: 'utf8mb4',
    defaultScope: {
      where: {
        status: 1,
      },
    },
    scopes: {
      deleted: {
        where: {
          status: 0,
        },
      },
      all: {
        where: {},
      },
    },
  });
  model.associate = () => {
    app.model.Article.belongsToMany(app.model.User, { as: 'likeUsers', through: model, foreignKey: 'articleId' });
    app.model.User.belongsToMany(app.model.Article, { as: 'likeArticles', through: model, foreignKey: 'userId' });
    // model.sync({ alter: true });
  };
  return model;
};
